<template>
  <div>
    <div class="top-container">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>【{{ props.menuName }}】权限维护</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-table
      ref="tableRef"
      :data="tableData"
      row-key="menuId"
      empty-text="暂无数据"
      border
      style="width: 100%"
      @select="handleSelect"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="menuName" label="权限名称" width="200" align="center" />
      <el-table-column prop="permissionCode" label="权限编码" align="center" />
    </el-table>
  </div>
</template>

<script setup lang="ts">
import { menuApi, roleApi } from '@/api'
import { MenuFindDTO, SysMenu } from '@/api/system/menuType'
import { PermissionMenu, SysRolePermission } from '@/api/system/roleTyppe'
import { MenuTypeEnum } from '@/enums/dictEnum'
import { ElMessage, TableInstance } from 'element-plus'
import { nextTick, onMounted, ref, useTemplateRef, watch } from 'vue'

// Props定义
interface Props {
  menuId: string
  menuName: string
  roleId: string
}

// 父组件传参
const props = withDefaults(defineProps<Props>(), {
  menuId: '',
  roleId: '',
  menuName: ''
})

// 表格实例
const tableRef = useTemplateRef<TableInstance>('tableRef')

// 表格数据
const tableData = ref<PermissionMenu[]>([])

// 角色对应权限列表
const rolePermissionList = ref<SysRolePermission[]>([])

/**
 * 查询权限列表
 */
const findPermissionList = async () => {
  const params: MenuFindDTO = {
    parentId: props.menuId,
    menuType: MenuTypeEnum.BUTTON
  }
  menuApi
    .findMenuList(params)
    .then((res: any) => {
      tableData.value = res || []
      findRolePermissionList()
    })
    .catch((err: any) => {
      ElMessage.error(err || '查询权限列表失败')
    })
}

/**
 * 查询角色权限列表
 */
const findRolePermissionList = async () => {
  if (!props.roleId || !props.menuId) {
    rolePermissionList.value = []
    tableRef.value?.clearSelection()
    return
  }
  roleApi
    .findRolePermissionList(props.roleId, props.menuId)
    .then((res: any) => {
      rolePermissionList.value = res || []
      tableRef.value?.clearSelection()
      nextTick(() => {
        rolePermissionList.value.forEach((row) => {
          const menu = tableData.value.find((item) => item.menuId === row.permissionId)
          if (menu?.menuId) {
            menu.checked = true
            tableRef.value?.toggleRowSelection(menu, true)
          }
        })
      })
    })
    .catch((err: any) => {
      ElMessage.error(err || '查询角色权限列表失败')
    })
}

/**
 * 选择权限
 */
const handleSelect = (val: any[], row: any) => {
  row.checked = val.includes(row)
  if (row.checked) {
    addRolePermission(row)
  } else {
    deleteRolePermission(row)
  }
}

const addRolePermission = async (row: any) => {
  const params: SysRolePermission = {
    roleId: props.roleId,
    menuId: props.menuId,
    permissionId: row.menuId
  }
  roleApi
    .addRolePermission(params)
    .then((res: any) => {
      ElMessage.success('添加角色权限成功')
    })
    .catch((err: any) => {
      ElMessage.error(err || '添加角色权限失败')
    })
    .finally(() => {
      findRolePermissionList()
    })
}

const deleteRolePermission = async (row: any) => {
  const params: SysRolePermission = {
    roleId: props.roleId,
    menuId: props.menuId,
    permissionId: row.menuId
  }
  roleApi
    .deleteRolePermission(params)
    .then((res: any) => {
      ElMessage.success('删除角色权限成功')
    })
    .catch((err: any) => {
      ElMessage.error(err || '删除角色权限失败')
    })
    .finally(() => {
      findRolePermissionList()
    })
}

watch(
  () => props.roleId,
  () => {
    tableData.value = []
  }
)

watch(
  () => props.menuId,
  (newVal) => {
    console.log('menuId 变化:', newVal)

    findPermissionList()
  }
)
</script>

<style scoped lang="less">
.top-container {
  display: flex;
  align-items: center;
  height: 32px;
  margin-bottom: 10px;
}
</style>
